package ru.spb.osll.myfit.client.widget;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.TextBox;

public class CellTextBox extends TextBox {

    private String rawText = "";
    private String parsedText = "";

    public CellTextBox() {
      this.addValueChangeHandler(new ValueChangeHandler<String>() {
          @Override
          public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) {
              if(!isReadOnly())
                  setRawText(stringValueChangeEvent.getValue());
          }
      });
    }

    /**
     * 
     * @param rawText
     * @param parsedText
     */
    public CellTextBox(String rawText, String parsedText) {
      this();
      this.parsedText = parsedText;
      this.rawText = rawText;
      setReadOnly(true);
    } 
       
    /**
     * 
     */
    public void setReadOnly(boolean isReadOnly) {
      super.setReadOnly(isReadOnly);
      updateVisibleText();
    }

    /**
     * 
     */
    private void updateVisibleText(){
      if(isReadOnly()){
        setVisibleLength(parsedText.length());
        super.setText(parsedText); 
      }else{
        setVisibleLength(rawText.length());
        super.setText(rawText);
      }
    }

    /**
     * 
     * @param parsedText
     */
    public void setParsedText(String parsedText) {
      this.parsedText = parsedText;
      updateVisibleText();
    }

    @Override
    public void setVisibleLength(int length) {
      length = length <= 0 ? 1 : length;
      super.setVisibleLength(length);
    }
    /**
     * 
     */
    public void setText(String text){
      if(isReadOnly()){
        setParsedText(text); 
      }else{
        int cursorPos = getCursorPos();
        setRawText(text);
        setCursorPos(cursorPos);
      }
    }

    /**
     * 
     * @param rawText
     */
    public void setRawText(String rawText) {
      this.rawText = rawText;
      updateVisibleText();
    }
    
    /**
     * 
     * @return
     */
    public String getRawText(){
      return rawText;
    }
    
    /**
     * 
     * @return
     */
    public String getParsedText(){
      return parsedText;
    }

    /**
     * 
     */
    public String getText(){
      if(isReadOnly()){
        return parsedText;
      }else{
        return super.getText();
        
       // rawText = super.getText();
       // return rawText;
      }
      //return rawText;
    }

}